<template>
  <div class="optimized-image">
    <NuxtImg
      :src="src"
      :alt="alt"
      :width="width"
      :height="height"
      :preset="preset"
      :format="format"
      :quality="quality"
      :loading="loading"
      :placeholder="placeholder"
      :sizes="sizes"
      :densities="densities"
      :class="imageClass"
      @load="onLoad"
      @error="onError"
    />
    <div v-if="showCaption && caption" class="optimized-image__caption">
      {{ caption }}
    </div>
  </div>
</template>

<script setup lang="ts">
interface Props {
  src: string;
  alt: string;
  width?: number;
  height?: number;
  preset?: 'avatar' | 'cover' | string;
  format?: 'webp' | 'avif' | 'png' | 'jpg';
  quality?: number;
  loading?: 'lazy' | 'eager';
  placeholder?: string | boolean;
  sizes?: string;
  densities?: string;
  imageClass?: string;
  caption?: string;
  showCaption?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  width: undefined,
  height: undefined,
  preset: undefined,
  format: 'webp',
  quality: 80,
  loading: 'lazy',
  placeholder: true,
  sizes: undefined,
  densities: '1x 2x',
  imageClass: '',
  caption: '',
  showCaption: false,
});

const emit = defineEmits<{
  load: [event: Event];
  error: [event: Event];
}>();

const onLoad = (event: Event) => {
  emit('load', event);
};

const onError = (event: Event) => {
  emit('error', event);
  console.warn('图片加载失败:', props.src);
};
</script>

<style scoped>
.optimized-image {
  display: inline-block;
}

.optimized-image img {
  max-width: 100%;
  height: auto;
  display: block;
}

.optimized-image__caption {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
  text-align: center;
}
</style>
